"""父类， 公共操作放置这里"""
import time

from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    _BASE_URL = ""

    def __init__(self, base_driver=None):
        if base_driver:
            self.driver = base_driver
        else:
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(5)
            self.driver.maximize_window()

        if not self.driver.current_url.startswith('http'):
            self.driver.get(self._BASE_URL)

    def do_find(self, by, locator=None):
        """
        获取单个元素
        :param by: By[ID, XPATH] 或者是带有By和locator的定位器
        :param locator: 定位器
        :return:
        """
        if locator:
            return self.driver.find_element(by, locator)
        else:
            return self.driver.find_element(*by)

    def do_finds(self, by, locator=None):
        """
        获取多个元素
        :param by: By[ID, XPATH] 或者是带有By和locator的定位器
        :param locator: 定位器
        :return:
        """
        if locator:
            return self.driver.find_elements(by, locator)
        else:
            return self.driver.find_elements(*by)

    def do_send_keys(self, msg, by, locator=None):
        ele = self.do_find(by, locator)
        ele.clear()
        ele.send_keys(msg)

    def do_quit(self):
        return self.driver.quit()

    def do_upload_pice(self, msg, by, locator=None):
        ele = self.do_find(by, locator)
        ele.send_keys(msg)

    def wait_web_driver(self, func):
        return WebDriverWait(self.driver, 10).until(func)

    def wait_element_until(self, locator):
        return WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located(locator))

    def wait_element_click(self, locator):
        time.sleep(1)
        return WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(locator))
